<template>
	<view class="content">
		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-form">
				<text class="yticon icon-sousuo"></text>
				<input 
					class="search-input" 
					type="text" 
					v-model="keyword" 
					placeholder="请输入商品名称" 
					confirm-type="search"
					@confirm="doSearch"
				/>
				<text class="yticon icon-guanbi" v-if="keyword" @click="keyword=''"></text>
			</view>
			<view class="search-btn" @click="doSearch">搜索</view>
		</view>
		
		<!-- 搜索历史 -->
		<view class="search-content" v-if="!showResult">
			<view class="search-history" v-if="historyList.length > 0">
				<view class="history-title">
					<text>搜索历史</text>
					<text class="clear-history" @click="clearHistory">清除</text>
				</view>
				<view class="history-list">
					<view 
						class="history-item"
						v-for="(item, index) in historyList" 
						:key="index"
						@click="keywordSearch(item)"
					>
						{{item}}
					</view>
				</view>
			</view>
			
			<!-- 热门搜索 -->
			<view class="search-hot">
				<view class="hot-title">热门搜索</view>
				<view class="hot-list">
					<view 
						class="hot-item"
						v-for="(item, index) in hotList" 
						:key="index"
						@click="keywordSearch(item)"
					>
						{{item}}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 搜索结果 -->
		<view class="search-result" v-else>
			<view class="result-header">
				<view 
					class="filter-item" 
					:class="{active: filterIndex === 0}"
					@click="changeFilter(0)"
				>
					综合
				</view>
				<view 
					class="filter-item" 
					:class="{active: filterIndex === 1}"
					@click="changeFilter(1)"
				>
					新品
				</view>
				<view 
					class="filter-item" 
					:class="{active: filterIndex === 2}"
					@click="changeFilter(2)"
				>
					销量
				</view>
				<view class="filter-item price" :class="{active: filterIndex === 3}" @click="changeFilter(3)">
					价格
					<view class="price-arrows">
						<text class="yticon icon-shang" :class="{active: priceOrder === 3}"></text>
						<text class="yticon icon-xia" :class="{active: priceOrder === 4}"></text>
					</view>
				</view>
			</view>
			
			<view class="result-list">
				<view 
					class="result-item"
					v-for="(item, index) in productList" 
					:key="index"
					@click="navToDetail(item)"
				>
					<view class="item-image">
						<image :src="item.pic" mode="aspectFill"></image>
					</view>
					<view class="item-content">
						<text class="item-title">{{item.name}}</text>
						<text class="item-subtitle">{{item.subTitle}}</text>
						<text class="item-price">¥{{item.price}}</text>
					</view>
				</view>
			</view>
			
			<uni-load-more :status="loadingType"></uni-load-more>
		</view>
		
		<!-- 空白结果提示 -->
		<view class="empty" v-if="showResult && productList.length === 0">
			<image src="/static/emptySearch.png" mode="aspectFit"></image>
			<text>没有找到相关商品，换个关键词试试吧~</text>
		</view>
	</view>
</template>

<script>
	import { searchProductList } from '@/api/product.js';
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	
	// 排序常量
	const SORT_BY_RELEVANCE = 0;  // 按相关度
	const SORT_BY_NEW = 1;        // 按新品
	const SORT_BY_SALES = 2;      // 按销量
	const SORT_BY_PRICE_ASC = 3;  // 价格从低到高
	const SORT_BY_PRICE_DESC = 4; // 价格从高到低
	
	export default {
		components: {
			uniLoadMore
		},
		data() {
			return {
				keyword: '',
				historyList: [],
				hotList: ['手机', '笔记本', '耳机', '平板', '手表', '相机'],
				showResult: false,
				filterIndex: 0,
				priceOrder: 0, // 价格排序状态：0:不按价格排序 3:价格从低到高 4:价格从高到低
				productList: [],
				searchParam: {
					keyword: '',
					pageNum: 1, // 后端API从1开始
					pageSize: 5, // 默认每页5条
					sort: SORT_BY_RELEVANCE // 使用常量定义排序选项
				},
				loadingType: 'more'
			}
		},
		onLoad(options) {
			// 如果有关键词参数，直接搜索
			if(options.keyword) {
				this.keyword = options.keyword;
				this.doSearch();
			}
			
			// 获取历史搜索记录
			let historyList = uni.getStorageSync('searchHistory');
			if(historyList) {
				this.historyList = JSON.parse(historyList);
			}
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.searchParam.pageNum = 1; // 重置为第1页
			this.loadData('refresh');
		},
		onReachBottom() {
			if(this.loadingType === 'nomore') {
				return;
			}
			this.searchParam.pageNum++; // 页码加1
			this.loadData();
		},
		methods: {
			// 执行搜索
			doSearch() {
				if(!this.keyword.trim()) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					});
					return;
				}
				
				// 保存到历史记录
				this.saveSearchHistory();
				
				// 重置搜索参数，只保留关键词
				this.searchParam = {
					keyword: this.keyword,
					pageNum: 1, // 后端API从1开始
					pageSize: 5, // 默认每页5条
					sort: SORT_BY_RELEVANCE // 默认按相关度排序
				};
				
				// 重置筛选UI状态
				this.filterIndex = 0;
				this.priceOrder = 0;
				this.showResult = true;
				
				// 搜索数据
				this.loadData('refresh');
			},
			
			// 使用关键词搜索
			keywordSearch(keyword) {
				this.keyword = keyword;
				this.doSearch();
			},
			
			// 保存搜索历史
			saveSearchHistory() {
				const keyword = this.keyword.trim();
				
				// 如果已存在，先删除旧记录
				let index = this.historyList.findIndex(item => item === keyword);
				if(index !== -1) {
					this.historyList.splice(index, 1);
				}
				
				// 将新搜索添加到开头
				this.historyList.unshift(keyword);
				
				// 最多保存10条记录
				if(this.historyList.length > 10) {
					this.historyList = this.historyList.slice(0, 10);
				}
				
				// 保存到本地存储
				uni.setStorageSync('searchHistory', JSON.stringify(this.historyList));
			},
			
			// 清除历史记录
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '确定要清除所有搜索历史吗？',
					success: (res) => {
						if(res.confirm) {
							this.historyList = [];
							uni.removeStorageSync('searchHistory');
						}
					}
				})
			},
			
			// 切换筛选条件
			changeFilter(index) {
				this.filterIndex = index;
				
				// 根据筛选条件修改排序方式
				if(index === 0) {
					// 综合排序（按相关度）
					this.searchParam.sort = SORT_BY_RELEVANCE;
					this.priceOrder = 0;
				} else if(index === 1) {
					// 新品排序
					this.searchParam.sort = SORT_BY_NEW;
					this.priceOrder = 0;
				} else if(index === 2) {
					// 销量排序
					this.searchParam.sort = SORT_BY_SALES;
					this.priceOrder = 0;
				} else if(index === 3) {
					// 价格排序，切换升序/降序
					if(this.priceOrder === 0 || this.priceOrder === SORT_BY_PRICE_DESC) {
						this.priceOrder = SORT_BY_PRICE_ASC;  // 价格从低到高
						this.searchParam.sort = SORT_BY_PRICE_ASC;
					} else {
						this.priceOrder = SORT_BY_PRICE_DESC;  // 价格从高到低
						this.searchParam.sort = SORT_BY_PRICE_DESC;
					}
				}
				
				// 确保sort是数字类型
				this.searchParam.sort = Number(this.searchParam.sort);
				
				// 重新加载第一页数据
				this.searchParam.pageNum = 1; // 后端API从1开始
				this.loadData('refresh');
			},
			
			// 加载数据
			loadData(type) {
				// 如果是刷新，清空列表
				if(type === 'refresh') {
					this.productList = [];
					this.loadingType = 'loading';
				}
				
				// 创建新的参数对象，过滤掉null值
				const params = {};
				Object.keys(this.searchParam).forEach(key => {
					if (this.searchParam[key] !== null && this.searchParam[key] !== undefined) {
						// 确保keyword是直接使用中文，而不是URL编码的字符串
						params[key] = this.searchParam[key];
					}
				});
				
				// 打印实际发送的参数
				console.log('搜索参数：', params);
				
				// 确保URL不会对中文参数自动编码
				searchProductList(params).then(res => {
					// 处理CommonResult<CommonPage<PmsProduct>>格式的响应
					console.log('搜索结果：', res);
					
					if (!res.data) {
						this.loadingType = 'nomore';
						return;
					}
					
					// 处理CommonResult<CommonPage<PmsProduct>>格式的响应
					let result = res.data;
					let data = [];
					
					// 提取列表数据
					if (result.list) {
						// 如果返回的是CommonPage格式
						data = result.list;
					} else if (Array.isArray(result)) {
						// 如果直接返回了数组
						data = result;
					}
					
					// 处理请求结果
					if(type === 'refresh') {
						this.productList = data;
					} else {
						this.productList = this.productList.concat(data);
					}
					
					// 判断是否还有更多数据
					if(data.length < this.searchParam.pageSize) {
						this.loadingType = 'nomore';
					} else {
						this.loadingType = 'more';
					}
					
					// 如果是下拉刷新，结束刷新状态
					if(type === 'refresh') {
						uni.stopPullDownRefresh();
					}
				}).catch((error) => {
					console.error('搜索请求失败：', error);
					this.handleApiError(error);
					if(type === 'refresh') {
						uni.stopPullDownRefresh();
					}
					this.loadingType = 'more';
				});
			},
			
			// 处理API错误
			handleApiError(error) {
				let errorMsg = '搜索请求失败';
				
				// 检查是否有详细错误消息
				if (error && error.message) {
					errorMsg = error.message;
					
					// 针对参数类型错误提供更具体的处理
					if (error.message.includes('MethodArgumentTypeMismatchException') || 
						error.message.includes('NumberFormatException')) {
						// 重置可能导致问题的参数
						if (this.searchParam.brandId !== undefined) {
							delete this.searchParam.brandId;
						}
						if (this.searchParam.productCategoryId !== undefined) {
							delete this.searchParam.productCategoryId;
						}
						errorMsg = '搜索参数格式有误，已重置筛选条件';
					}
				}
				
				// 显示错误提示
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 2000
				});
			},
			
			// 跳转到商品详情
			navToDetail(item) {
				uni.navigateTo({
					url: `/pages/product/product?id=${item.id}`
				});
			},
			
			// 设置品牌筛选
			setBrandFilter(brandId) {
				// 使用number类型，避免字符串类型不匹配
				this.searchParam.brandId = brandId ? Number(brandId) : undefined;
				this.searchParam.pageNum = 1; // 重置为第1页
				this.loadData('refresh');
			},
			
			// 设置分类筛选
			setCategoryFilter(categoryId) {
				// 使用number类型，避免字符串类型不匹配
				this.searchParam.productCategoryId = categoryId ? Number(categoryId) : undefined;
				this.searchParam.pageNum = 1; // 重置为第1页
				this.loadData('refresh');
			},
			
			// 重置所有筛选条件
			resetFilters() {
				// 只保留关键词，重置其他所有条件
				const keyword = this.searchParam.keyword;
				this.searchParam = {
					keyword: keyword,
					pageNum: 1, // 重置为第1页
					pageSize: 5,
					sort: SORT_BY_RELEVANCE
				};
				this.filterIndex = 0;
				this.priceOrder = 0;
				this.loadData('refresh');
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f8f8f8;
	}
	
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	/* 搜索框样式 */
	.search-box {
		width: 100%;
		background-color: #fff;
		padding: 20upx 30upx;
		display: flex;
		align-items: center;
		position: sticky;
		top: 0;
		z-index: 10;
		
		.search-form {
			display: flex;
			align-items: center;
			flex: 1;
			height: 70upx;
			background-color: #f5f5f5;
			border-radius: 35upx;
			padding: 0 20upx;
			
			.yticon {
				color: #909399;
				font-size: 32upx;
			}
			
			.search-input {
				flex: 1;
				height: 60upx;
				line-height: 60upx;
				margin: 0 20upx;
				font-size: 28upx;
				color: #333;
			}
		}
		
		.search-btn {
			width: 120upx;
			height: 70upx;
			line-height: 70upx;
			text-align: center;
			font-size: 28upx;
			color: #fff;
			background-color: $uni-color-primary;
			border-radius: 35upx;
			margin-left: 20upx;
		}
	}
	
	/* 搜索历史样式 */
	.search-content {
		width: 100%;
		padding: 20upx 30upx;
		
		.search-history {
			margin-bottom: 30upx;
			
			.history-title {
				display: flex;
				justify-content: space-between;
				font-size: 28upx;
				color: #606266;
				margin-bottom: 20upx;
				
				.clear-history {
					color: $uni-color-primary;
				}
			}
			
			.history-list {
				display: flex;
				flex-wrap: wrap;
				
				.history-item {
					background-color: #f1f1f1;
					padding: 10upx 20upx;
					border-radius: 30upx;
					margin-right: 20upx;
					margin-bottom: 20upx;
					font-size: 26upx;
					color: #303133;
				}
			}
		}
		
		.search-hot {
			.hot-title {
				font-size: 28upx;
				color: #606266;
				margin-bottom: 20upx;
			}
			
			.hot-list {
				display: flex;
				flex-wrap: wrap;
				
				.hot-item {
					background-color: #f1f1f1;
					padding: 10upx 20upx;
					border-radius: 30upx;
					margin-right: 20upx;
					margin-bottom: 20upx;
					font-size: 26upx;
					color: #303133;
				}
			}
		}
	}
	
	/* 搜索结果样式 */
	.search-result {
		width: 100%;
		
		.result-header {
			display: flex;
			align-items: center;
			height: 80upx;
			background-color: #fff;
			border-bottom: 1px solid #eee;
			position: sticky;
			top: 110upx;
			z-index: 9;
			
			.filter-item {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
				font-size: 28upx;
				color: #606266;
				position: relative;
				
				&.active {
					color: $uni-color-primary;
				}
				
				&.price {
					display: flex;
					flex-direction: row;
					
					.price-arrows {
						display: flex;
						flex-direction: column;
						margin-left: 8upx;
						
						.yticon {
							font-size: 16upx;
							line-height: 1;
							
							&.active {
								color: $uni-color-primary;
							}
						}
					}
				}
			}
		}
		
		.result-list {
			width: 100%;
			padding: 20upx;
			
			.result-item {
				display: flex;
				padding: 20upx;
				background-color: #fff;
				border-radius: 12upx;
				margin-bottom: 20upx;
				box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
				
				.item-image {
					width: 200upx;
					height: 200upx;
					margin-right: 20upx;
					
					image {
						width: 100%;
						height: 100%;
						border-radius: 8upx;
					}
				}
				
				.item-content {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					
					.item-title {
						font-size: 30upx;
						color: #303133;
						line-height: 1.4;
						height: 84upx;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}
					
					.item-subtitle {
						font-size: 24upx;
						color: #909399;
						line-height: 1.4;
					}
					
					.item-price {
						font-size: 34upx;
						color: $uni-color-primary;
						font-weight: bold;
					}
				}
			}
		}
	}
	
	/* 空白结果提示样式 */
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100upx 0;
		
		image {
			width: 240upx;
			height: 240upx;
			margin-bottom: 30upx;
		}
		
		text {
			font-size: 28upx;
			color: #909399;
		}
	}
</style> 